<?php
/**
* 用户银行卡模块Api Service
*
* 用户银行卡模块Api Service的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Statistics;

use Log;

use App\Services\Tool\DataBase\SQL;
use App\Services\Tool\GeneralTool;
use App\Services\UserService\UserTool;
use App\Services\Tool\Statistics\UserBankTool;
use App\Services\Tool\Pay\AlipayTool;
use App\Services\Tool\XCZ\SMS\SMS;

class UserBankApi{


    function __construct(UserTool $userTool,
                         UserBankTool $userBankTool,
                         AlipayTool $alipay){
        $this->userTool     = $userTool;
        $this->userBankTool = $userBankTool;
        $this->alipay       = $alipay;
    }

    /**
        银行卡绑定
        参数：
            user_id         用户编号
            card_holder     持卡人
            bank_card_no    银行卡号
            phone           手机号
            bank_name       银行名称
            bank_branch     开户支行
     */
    function userBankCardBinding($input){
        if(!isset($input['user_id']))
            return GeneralTool::createResult('','M00002');
        else if(!$this->userTool->isUser($input['user_id']))
            return GeneralTool::createResult('','M05001');
        else if($this->userBankTool->getUserBankCardCount(['user_id'=>$input['user_id']])>0)
            return GeneralTool::createResult('','M06014');
        else if(!isset($input['card_holder'])||trim($input['card_holder'])=="")
            return GeneralTool::createResult('','M06002');
        else if(!isset($input['bank_card_no'])||trim($input['bank_card_no'])=="")
            return GeneralTool::createResult('','M06003');
        else if(!isset($input['phone'])||trim($input['phone'])=="")
            return GeneralTool::createResult('','M06004');
        else if(!isset($input['bank_name'])||trim($input['bank_name'])=="")
            return GeneralTool::createResult('','M06005');
        else if(!isset($input['bank_branch'])||trim($input['bank_branch'])=="")
            return GeneralTool::createResult('','M06006');
        else if(!isset($input['prov'])||trim($input['prov'])=="")
            return GeneralTool::createResult('','M06021');
        else if(!isset($input['city'])||trim($input['city'])=="")
            return GeneralTool::createResult('','M06022');
        else if(!isset($input['area']))
            return GeneralTool::createResult('','M06023');
        else if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['card_holder'])||
                !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['card_holder']))
            return GeneralTool::createResult('','M06007');
        else if(mb_strlen(trim($input['bank_card_no']),'utf-8')>19||mb_strlen(trim($input['bank_card_no']),'utf-8')<16)
            return GeneralTool::createResult('','M06008');
        else if(!is_numeric($input['bank_card_no']))
            return GeneralTool::createResult('','M06009');
        else if(!GeneralTool::Luhn($input['bank_card_no']))
            return GeneralTool::createResult('','M06010');
        else if(!preg_match("/1[34578]{1}\d{9}$/", $input['phone']))
            return GeneralTool::createResult('','M06011');
        else if(mb_strlen(trim($input['bank_name']),'utf-8')<2||
                mb_strlen(trim($input['bank_name']),'utf-8')>20||
                !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['bank_name']))
            return GeneralTool::createResult('','M06012');
        else if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['bank_name']))
            return GeneralTool::createResult('','M06012');
        else if(mb_strlen(trim($input['bank_branch']),'utf-8')<3||
                mb_strlen(trim($input['bank_branch']),'utf-8')>25||
                preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['bank_branch']))
            return GeneralTool::createResult('','M06013');
        else if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['prov']))
            return GeneralTool::createResult('','M06024');
        else if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['city']))
            return GeneralTool::createResult('','M06025');
        else if(trim($input['area']) != '' && !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['area']))
            return GeneralTool::createResult('','M06026');
        try{

            //校验该用户今天是否失败超过次数
            if($this->userBankTool->bank_card_veryfy_fail_time($input))
                return GeneralTool::createResult('','M05062');
            //校验持卡人银行卡
            if(!$this->userBankTool->bankCardNoHolderVeryfy(['card_holder'  => $input['card_holder'],
                                                             'bank_card_no' => $input['bank_card_no'],
                                                             'user_id'      => $input['user_id']]))
                 return GeneralTool::createResult('','M06015');

            //添加银行卡
            $result = $this->userBankTool->bindingUserBankCard(['user_id'      => $input['user_id'],
                                                                'card_holder'  => $input['card_holder'],
                                                                'bank_card_no' => $input['bank_card_no'],
                                                                'phone'        => $input['phone'],
                                                                'bank_name'    => $input['bank_name'],
                                                                'bank_branch'  => $input['bank_branch'],
                                                                'prov'         => $input['prov'],
                                                                'city'         => $input['city'],
                                                                'area'         => $input['area'],
                                                                'result'       => 2,
                                                                'state'        => 1]);
            if( $result == 0 ) return GeneralTool::createResult('','M00001');
            $info   = $this->userBankTool->getUserBankCard(['user_id'=>$input['user_id']]);

            return GeneralTool::createResult($info,'M00000');

        }catch(\Exception $e){
            Log::info($e);
            return GeneralTool::createResult('','M00003');
        }
    }

    /**
        修改银行卡信息
        参数：
            user_id         用户编号
            user_card_id    用户银行卡信息编号
            card_holder     持卡人
            bank_card_no    银行卡号
            phone           手机号
            bank_name       银行名称
            bank_branch     开户支行
            prov            省份
            city            城市
     */
    function updateBankCardInfo($input){
        return GeneralTool::createResult('','M00001');
        if(!isset($input['user_id']))
            return GeneralTool::createResult('','M00002');
        else if(!$this->userTool->isUser($input['user_id']))
            return GeneralTool::createResult('','M05001');
        else if($this->userBankTool->getUserBankCardCount(['user_id'=>$input['user_id'],'id'=>$input['user_card_id'],'state'=>1])==0)
            return GeneralTool::createResult('','M06016');
        else if($this->userBankTool->getUserBankCardCount(['user_id'=>$input['user_id'],'id'=>$input['user_card_id'],'state'=>1,'result'=>1])==1)
            return GeneralTool::createResult('','M06019');
        else if(!isset($input['card_holder'])||trim($input['card_holder'])=="")
            return GeneralTool::createResult('','M06002');
        else if(!isset($input['bank_card_no'])||trim($input['bank_card_no'])=="")
            return GeneralTool::createResult('','M06003');
        else if(!isset($input['phone'])||trim($input['phone'])=="")
            return GeneralTool::createResult('','M06004');
        else if(!isset($input['bank_name'])||trim($input['bank_name'])=="")
            return GeneralTool::createResult('','M06005');
        else if(!isset($input['bank_branch'])||trim($input['bank_branch'])=="")
            return GeneralTool::createResult('','M06006');
        else if(!isset($input['prov'])||trim($input['prov'])=="")
            return GeneralTool::createResult('','M06021');
        else if(!isset($input['city'])||trim($input['city'])=="")
            return GeneralTool::createResult('','M06022');
        else if(!isset($input['area']))
            return GeneralTool::createResult('','M06023');
        else if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['card_holder'])||
                !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['card_holder']))
            return GeneralTool::createResult('','M06007');
        else if(mb_strlen(trim($input['bank_card_no']),'utf-8')>19||mb_strlen(trim($input['bank_card_no']),'utf-8')<16)
            return GeneralTool::createResult('','M06008');
        else if(!is_numeric($input['bank_card_no']))
            return GeneralTool::createResult('','M06009');
        else if(!GeneralTool::Luhn($input['bank_card_no']))
            return GeneralTool::createResult('','M06010');
        else if(!preg_match("/1[34578]{1}\d{9}$/", $input['phone']))
            return GeneralTool::createResult('','M06011');
        else if(mb_strlen(trim($input['bank_name']),'utf-8')<2||
                mb_strlen(trim($input['bank_name']),'utf-8')>20||
                !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['bank_name']))
            return GeneralTool::createResult('','M06012');
        else if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['bank_name']))
            return GeneralTool::createResult('','M06012');
        else if(mb_strlen(trim($input['bank_branch']),'utf-8')<3||
                mb_strlen(trim($input['bank_branch']),'utf-8')>25||
                preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['bank_branch']))
            return GeneralTool::createResult('','M06013');
        else if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['prov']))
            return GeneralTool::createResult('','M06024');
        else if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['city']))
            return GeneralTool::createResult('','M06025');
        else if(trim($input['area']) != '' && !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['area']))
            return GeneralTool::createResult('','M06026');

         try{

            //修改银行卡
            $result = $this->userBankTool->updateUserBankCard(['user_id'      => $input['user_id'],
                                                               'user_card_id' => $input['user_card_id'],
                                                               'card_holder'  => $input['card_holder'],
                                                               'bank_card_no' => $input['bank_card_no'],
                                                               'phone'        => $input['phone'],
                                                               'bank_name'    => $input['bank_name'],
                                                               'bank_branch'  => $input['bank_branch'],
                                                               'prov'         => $input['prov'],
                                                               'city'         => $input['city'],
                                                               'area'         => $input['area'],
                                                               'updated_at'   => time()]);

            if( $result == 0 ) return GeneralTool::createResult('','M00001');

            $info   = $this->userBankTool->getUserBankCard(['user_id'=>$input['user_id']]);

            return GeneralTool::createResult($info,'M00000');

        }catch(\Exception $e){
            Log::info($e);
            return GeneralTool::createResult('','M00003');
        }
    }



    /**
     * version 2.0
     */

    /**
     * 银行卡列表
     * 参数：
     *     user_id      用户编号
     *     page         页码
     *     per_page     每页显示数据量
     */
    function user_bank_list($input){

        if(!isset($input['user_id']))
            return GeneralTool::createResult('','M00002');

        if(!$this->userTool->isUser($input['user_id']))
            return GeneralTool::createResult('','M05001');

        $arr['data']           = $this->userBankTool->user_bank_list($input);
        $arr['has_password']   = UserBankTool::user_has_withdraw_password($input) ? 0 : 1;
        return GeneralTool::createResult($arr, 'M00000');
    }

    /**
     * 发送验证码
     * 参数：
     *     user_id          用户编号
     *     type             验证码用途 1
     */
    function sms_set_password_to_pay($input){
        if(!isset($input['user_id']))
            return GeneralTool::createResult('', 'M00002');
        $phone = UserTool::getPhoneByUserid($input['user_id']);
        if($phone == '') return GeneralTool::createResult('', 'M06027');
        $can = $this->userBankTool->code_can_send($input);
        if($can['state'] != 'M00000') return $can;
        $input['phone'] = $phone;
        $result = SMS::run($input);
        if($result['state'] == '000000') $this->userBankTool->save_code(['type'    => $input['type'],
                                                                         'user_id' => $input['user_id'],
                                                                         'code'    => $result['code']]);
        return GeneralTool::createResult('', ($result['state'] == '000000' ? 'M00000' : 'M00001'));
    }

    /**
     * 设置提现密码
     * 参数：
     *     user_id          用户编号
     *     password         密码
     *     confirm_password 确认密码
     *     captcha          验证码
     */
    function set_password($input){
        if(!isset($input['user_id']) ||
            !isset($input['password']) || trim($input['password']) == '' ||
            !isset($input['confirm_password']) || trim($input['confirm_password'])  == '' ||
            !isset($input['captcha']))
            return GeneralTool::createResult('', 'M00002');
        if(UserTool::getPhoneByUserid($input['user_id']) == '')
            return GeneralTool::createResult('', 'M06027');
        if(!preg_match("/(0|[1-9][0-9]{5})$/", $input['password']))
            return GeneralTool::createResult('', 'M06029');
        if($input['password'] != $input['confirm_password'])
            return GeneralTool::createResult('', 'M06030');

        $verfy = $this->userBankTool->verfy_captcha(['user_id' => $input['user_id'],
                                                     'type'    => 1,
                                                     'state'   => 1,
                                                     'code'    => $input['captcha']]);
        if($verfy['state'] != 'M00000') return $verfy;
        $result = $this->userBankTool->update_user_widthdraw(['user_id' => $input['user_id'], 'withdraw_password' => '', 'state' => 1],
                                                             ['withdraw_password' => UserBankTool::md5pwd($input['password'],$input['user_id'])]);
        if($result) $this->userBankTool->clearn_captcha(['user_id' => $input['user_id'],
                                                         'type'    => 1,
                                                         'state'   => 1]);
        return GeneralTool::createResult('', ($result ? 'M00000' : 'M00001'));
    }

    /**
     * 重置提现密码
     * 参数：
     *     user_id          用户编号
     *     old_password     旧密码
     *     password         密码
     *     confirm_password 确认密码
     *     captcha          验证码
     */
    function reset_password($input){
        if(!isset($input['user_id']) ||
            !isset($input['password']) || trim($input['password']) == '' ||
            !isset($input['confirm_password']) || trim($input['confirm_password'])  == '' ||
            !isset($input['old_password']) || trim($input['old_password']) == '' ||
            !isset($input['captcha']))
            return GeneralTool::createResult('', 'M00002');
        if(UserTool::getPhoneByUserid($input['user_id']) == '')
            return GeneralTool::createResult('', 'M06027');
        if(UserBankTool::user_has_withdraw_password($input))
            return GeneralTool::createResult('','M06036');
        if(!preg_match("/(0|[1-9][0-9]{5})$/", $input['password']))
            return GeneralTool::createResult('', 'M06029');
        if($input['password'] != $input['confirm_password'])
            return GeneralTool::createResult('', 'M06030');

        $verfy = $this->userBankTool->verfy_captcha(['user_id' => $input['user_id'],
                                                     'type'    => 2,
                                                     'state'   => 1,
                                                     'code'    => $input['captcha']]);
        if($verfy['state'] != 'M00000') return $verfy;
        $result = $this->userBankTool->update_user_widthdraw(['user_id' => $input['user_id'],
                                                              'withdraw_password' => UserBankTool::md5pwd($input['old_password'], $input['user_id']),
                                                              'state' => 1],
                                                             ['withdraw_password' => UserBankTool::md5pwd($input['password'],$input['user_id'])]);
        if($result) $this->userBankTool->clearn_captcha(['user_id' => $input['user_id'],
                                                         'type'    => 1,
                                                         'state'   => 1]);
        return GeneralTool::createResult('', ($result ? 'M00000' : 'M06034'));
    }

    /**
     * 忘记提现密码
     * 参数：
     *     user_id          用户编号
     *     captcha          验证码
     */
    function forget_password($input){
        if(!isset($input['user_id']) ||
            !isset($input['password']) || trim($input['password']) == '' ||
            !isset($input['confirm_password']) || trim($input['confirm_password'])  == '' ||
            !isset($input['captcha']))
            return GeneralTool::createResult('', 'M00002');
        if(UserTool::getPhoneByUserid($input['user_id']) == '')
            return GeneralTool::createResult('', 'M06027');
        if(!preg_match("/(0|[1-9][0-9]{5})$/", $input['password']))
            return GeneralTool::createResult('', 'M06029');
        if($input['password'] != $input['confirm_password'])
            return GeneralTool::createResult('', 'M06030');
        $verfy = $this->userBankTool->verfy_captcha(['user_id' => $input['user_id'],
                                                     'type'    => 1,
                                                     'state'   => 1,
                                                     'code'    => $input['captcha']]);
        if($verfy['state'] != 'M00000') return $verfy;
        $result = $this->userBankTool->update_user_widthdraw(['user_id' => $input['user_id'], 'state' => 1],
                                                             ['withdraw_password' => UserBankTool::md5pwd($input['password'],$input['user_id'])]);
        if($result) $this->userBankTool->clearn_captcha(['user_id' => $input['user_id'],
                                                         'type'    => 1,
                                                         'state'   => 1]);
        return GeneralTool::createResult('', 'M00000');
    }

    function test($input){
        $result = $input;
        dd($result);
        return $result;
    }

    /**
        银行卡绑定
        参数：
            user_id         用户编号
            card_holder     持卡人
            bank_card_no    银行卡号
            phone           手机号
            bank_name       银行名称
            bank_branch     开户支行
            password        密码
     */
    function new_bank_card($input){
        if(!isset($input['user_id']) || !isset($input['password']))
            return GeneralTool::createResult('','M00002');
        else if(UserTool::getPhoneByUserid($input['user_id']) == '')
            return GeneralTool::createResult('', 'M06027');
        else if(UserBankTool::user_has_withdraw_password($input))
            return GeneralTool::createResult('','M06036');
        else if(UserBankTool::verfy_withdraw_password($input) == 0)
            return GeneralTool::createResult('','M06035');
        else if(userBankTool::user_fail_count($input) >= env('VERFY_FAIL_TIME'))
            return GeneralTool::createResult('', 'M06033');
        else if(!isset($input['card_holder'])||trim($input['card_holder'])=="")
            return GeneralTool::createResult('','M06002');
        else if(!isset($input['bank_card_no'])||trim($input['bank_card_no'])=="")
            return GeneralTool::createResult('','M06003');
        else if($this->userBankTool->getUserBankCardCount(['user_id'=>$input['user_id'], 'bank_card_no' => $input['bank_card_no']]))
            return GeneralTool::createResult('','M06014');
        else if($this->userBankTool->getUserBankCardCount(['user_id'=>$input['user_id']]) >= UserBankTool::get_configs('user_bank_card_max'))
            return GeneralTool::createResult('','M06037');
        else if(!isset($input['phone'])||trim($input['phone'])=="")
            return GeneralTool::createResult('','M06004');
        else if(!isset($input['bank_name'])||trim($input['bank_name'])=="")
            return GeneralTool::createResult('','M06005');
        else if(!isset($input['bank_branch'])||trim($input['bank_branch'])=="")
            return GeneralTool::createResult('','M06006');
        else if(!isset($input['prov'])||trim($input['prov'])=="")
            return GeneralTool::createResult('','M06021');
        else if(!isset($input['city'])||trim($input['city'])=="")
            return GeneralTool::createResult('','M06022');
        else if(!isset($input['area']))
            return GeneralTool::createResult('','M06023');
        else if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['card_holder'])||
                !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['card_holder']))
            return GeneralTool::createResult('','M06007');
        else if(mb_strlen(trim($input['bank_card_no']),'utf-8')>19||mb_strlen(trim($input['bank_card_no']),'utf-8')<16)
            return GeneralTool::createResult('','M06008');
        else if(!is_numeric($input['bank_card_no']))
            return GeneralTool::createResult('','M06009');
        else if(!GeneralTool::Luhn($input['bank_card_no']))
            return GeneralTool::createResult('','M06010');
        else if(!preg_match("/1[34578]{1}\d{9}$/", $input['phone']))
            return GeneralTool::createResult('','M06011');
        else if(mb_strlen(trim($input['bank_name']),'utf-8')<2||
                mb_strlen(trim($input['bank_name']),'utf-8')>20||
                !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['bank_name']))
            return GeneralTool::createResult('','M06012');
        else if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['bank_name']))
            return GeneralTool::createResult('','M06012');
        else if(mb_strlen(trim($input['bank_branch']),'utf-8')<3||
                mb_strlen(trim($input['bank_branch']),'utf-8')>25||
                preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/",$input['bank_branch']))
            return GeneralTool::createResult('','M06013');
        else if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['prov']))
            return GeneralTool::createResult('','M06024');
        else if(!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['city']))
            return GeneralTool::createResult('','M06025');
        else if(trim($input['area']) != '' && !preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$input['area']))
            return GeneralTool::createResult('','M06026');
        try{

            //校验该用户今天是否失败超过次数
            if($this->userBankTool->bank_card_veryfy_fail_time($input))
                return GeneralTool::createResult('','M05062');
            //校验持卡人银行卡
            if(!$this->userBankTool->bankCardNoHolderVeryfy(['card_holder'  => $input['card_holder'],
                                                             'bank_card_no' => $input['bank_card_no'],
                                                             'user_id'      => $input['user_id']]))
                 return GeneralTool::createResult('','M06015');

            //添加银行卡
            $result = $this->userBankTool->bindingUserBankCard(['user_id'      => $input['user_id'],
                                                                'card_holder'  => $input['card_holder'],
                                                                'bank_card_no' => $input['bank_card_no'],
                                                                'phone'        => $input['phone'],
                                                                'bank_name'    => $input['bank_name'],
                                                                'bank_branch'  => $input['bank_branch'],
                                                                'prov'         => $input['prov'],
                                                                'city'         => $input['city'],
                                                                'area'         => $input['area'],
                                                                'result'       => 2,
                                                                'state'        => 1]);
            if( !$result ) return GeneralTool::createResult('','M00001');
            $info   = $this->userBankTool->get_user_bank_card(['id' => $result]);

            return GeneralTool::createResult($info,'M00000');

        }catch(\Exception $e){
            Log::info($e);
            return GeneralTool::createResult('','M00003');
        }
    }

    /**
     * 删除银行卡
     * 参数：
     *     user_id          用户编号
     *     user_card_id     用户银行卡编号
     *     password         密码
     */
    function delete_bank_card($input){
        if(!isset($input['user_id']) ||
            !isset($input['user_card_id']) ||
            !isset($input['password']))
            return GeneralTool::createResult('', 'M00002');
        if(UserTool::getPhoneByUserid($input['user_id']) == '')
            return GeneralTool::createResult('', 'M06027');
        if(UserBankTool::user_has_withdraw_password($input))
            return GeneralTool::createResult('','M06036');
        if(UserBankTool::verfy_withdraw_password($input) == 0)
            return GeneralTool::createResult('','M06035');
        if(userBankTool::user_fail_count($input) >= env('VERFY_FAIL_TIME'))
            return GeneralTool::createResult('', 'M06033');

        $result = SQL::update(['table' => 'user_bank_infos',
                               'where' => ['user_id' => $input['user_id'],
                                           'id'      => $input['user_card_id']],
                               'update'=> ['state'   => 0]]);
        return GeneralTool::CreateResult('', ($result ? 'M00000' : 'M06016'));
    }


}
